const db = require('../models');
const Comment = db.Comment;
const User = db.User;
const Post = db.Post;

/**
 * 评论服务层
 * 处理与评论相关的业务逻辑
 */
class CommentService {
  /**
   * 创建新评论
   * @param {Object} commentData - 评论数据
   * @returns {Promise<Object>} 创建的评论对象
   */
  async create(commentData) {
    return await Comment.create(commentData);
  }

  /**
   * 根据ID查找评论
   * @param {number} id - 评论ID
   * @returns {Promise<Object>} 评论对象
   */
  async findById(id) {
    return await Comment.findByPk(id, {
      include: [
        {
          model: User,
          as: 'author',
          attributes: ['id', 'username', 'avatar']
        },
        {
          model: Comment,
          as: 'replies',
          include: [
            {
              model: User,
              as: 'author',
              attributes: ['id', 'username', 'avatar']
            }
          ]
        }
      ]
    });
  }

  /**
   * 获取文章的评论列表
   * @param {number} postId - 文章ID
   * @param {Object} options - 查询选项
   * @returns {Promise<Object>} 包含评论列表和总数的对象
   */
  async findByPostId(postId, options = {}) {
    const { page = 1, limit = 10, status } = options;
    
    const query = {
      where: { 
        postId,
        parentId: null // 只获取顶级评论
      },
      include: [
        {
          model: User,
          as: 'author',
          attributes: ['id', 'username', 'avatar']
        },
        {
          model: Comment,
          as: 'replies',
          include: [
            {
              model: User,
              as: 'author',
              attributes: ['id', 'username', 'avatar']
            }
          ]
        }
      ],
      order: [['createdAt', 'DESC']],
      offset: (page - 1) * limit,
      limit: parseInt(limit)
    };
    
    // 根据状态筛选
    if (status) {
      query.where.status = status;
    }
    
    // 获取总数和数据
    const { count, rows } = await Comment.findAndCountAll(query);
    
    return {
      total: count,
      totalPages: Math.ceil(count / limit),
      currentPage: page,
      comments: rows
    };
  }

  /**
   * 获取用户的评论列表
   * @param {number} userId - 用户ID
   * @param {Object} options - 查询选项
   * @returns {Promise<Object>} 包含评论列表和总数的对象
   */
  async findByUserId(userId, options = {}) {
    const { page = 1, limit = 10, status } = options;
    
    const query = {
      where: { userId },
      include: [
        {
          model: User,
          as: 'author',
          attributes: ['id', 'username', 'avatar']
        },
        {
          model: Post,
          as: 'post',
          attributes: ['id', 'title', 'slug']
        }
      ],
      order: [['createdAt', 'DESC']],
      offset: (page - 1) * limit,
      limit: parseInt(limit)
    };
    
    // 根据状态筛选
    if (status) {
      query.where.status = status;
    }
    
    // 获取总数和数据
    const { count, rows } = await Comment.findAndCountAll(query);
    
    return {
      total: count,
      totalPages: Math.ceil(count / limit),
      currentPage: page,
      comments: rows
    };
  }

  /**
   * 更新评论
   * @param {number} id - 评论ID
   * @param {Object} commentData - 更新的评论数据
   * @returns {Promise<Object>} 更新结果
   */
  async update(id, commentData) {
    await Comment.update(commentData, {
      where: { id }
    });
    
    return this.findById(id);
  }

  /**
   * 删除评论（软删除）
   * @param {number} id - 评论ID
   * @returns {Promise<number>} 删除的记录数
   */
  async delete(id) {
    return await Comment.destroy({
      where: { id }
    });
  }

  /**
   * 更新评论状态
   * @param {number} id - 评论ID
   * @param {string} status - 新状态
   * @returns {Promise<Object>} 更新结果
   */
  async updateStatus(id, status) {
    return await Comment.update(
      { status },
      { where: { id } }
    );
  }

  /**
   * 获取待审核的评论列表
   * @param {Object} options - 查询选项
   * @returns {Promise<Object>} 包含评论列表和总数的对象
   */
  async getPendingComments(options = {}) {
    const { page = 1, limit = 10 } = options;
    
    const query = {
      where: { status: 'pending' },
      include: [
        {
          model: User,
          as: 'author',
          attributes: ['id', 'username', 'avatar']
        },
        {
          model: Post,
          as: 'post',
          attributes: ['id', 'title', 'slug']
        }
      ],
      order: [['createdAt', 'ASC']],
      offset: (page - 1) * limit,
      limit: parseInt(limit)
    };
    
    // 获取总数和数据
    const { count, rows } = await Comment.findAndCountAll(query);
    
    return {
      total: count,
      totalPages: Math.ceil(count / limit),
      currentPage: page,
      comments: rows
    };
  }
}

module.exports = new CommentService();